package org.tinygroup.restpractice.dao;

import static org.tinygroup.restpractice.pojo.UserTable.USER;
import static org.tinygroup.tinysqldsl.Select.*;

import java.util.List;

import org.tinygroup.restpractice.pojo.User;
import org.tinygroup.tinysqldsl.Delete;
import org.tinygroup.tinysqldsl.DslSession;
import org.tinygroup.tinysqldsl.Insert;
import org.tinygroup.tinysqldsl.Select;
import org.tinygroup.tinysqldsl.Update;

public class UserDaoImpl implements UserDao {

	private DslSession dslSession;

	public void setDslSession(DslSession dslSession) {
		this.dslSession = dslSession;
	}

	public User addUser(User user) {
		Insert insert = Insert.insertInto(USER).values(
				USER.NAME.value(user.getName()), USER.AGE.value(user.getAge()));

		return dslSession.executeAndReturnObject(insert, User.class);
	}

	public int updateUser(User user) {
		Update update = Update
				.update(USER)
				.set(USER.NAME.value(user.getName()),
						USER.AGE.value(user.getAge()))
				.where(USER.ID.eq(user.getId()));
		return dslSession.execute(update, true);
	}

	public int deleteUser(User user) {
		Delete delete = Delete.delete(USER).where(USER.ID.eq(user.getId()));
		return dslSession.execute(delete);
	}

	public List<User> queryUsers(User user) {
		if(user==null){
			user=new User();
		}
		Select select = Select.selectFrom(USER).where(
				and(USER.ID.equal(user.getId()),
						USER.NAME.like(user.getName()),
						USER.AGE.equal(user.getAge())));

		return dslSession.fetchList(select, User.class);
	}

	public User queryUserById(String id) {

		Select select = Select.selectFrom(USER).where(USER.ID.equal(id));

		return dslSession.fetchOneResult(select, User.class);
	}

}
